<script>
import MyHeader from './components/MyHeader'
// import MyItem from './components/MyItem'
import MyList from './components/MyList'
import MyFooter from './components/MyFooter'
import pubsub from 'pubsub-js'

export default {
  name: "App",
  data() {
    return {
      //定义一个任务,从任务缓存中获取任务,如果任务缓存为空就返回空数组
      todos: JSON.parse(localStorage.getItem('todos')) || [],
      allChecked: localStorage.getItem('allChecked') !== null ? (localStorage.getItem('allChecked') === 'true') : false,
    }
  },
  methods: {
    //添加一个todo
    addTodo(objTodo) {
      //将该任务添加到浏览器缓存中
      console.log('添加成功', objTodo.title)
      this.todos.unshift(objTodo)
    },

    //勾选or取消勾选一个todo
    changeCheck(_, id) {
      this.todos.forEach((todo) => {
        if (todo.id === id) {
          todo.done = !todo.done
        }
      })
    },

    //删除一个todo
    deleteTodo(id) {
      const index = this.todos.findIndex(todo => todo.id === id)
      let isConfim = window.confirm('你确定要删除' + (this.todos[index]).title)
      if (isConfim) {
        console.log(index)
        this.todos = this.todos.filter(todo => todo.id !== id)
        console.log('删除成功')
      }
    },

    //全选or取消勾选
    checkAllTodo(done) {
      console.log('传入的值为' + done)
      this.todos.forEach(todo => todo.done = done)
    },

    //删除已完成的todo
    clearAllTodo() {
      this.todos = this.todos.filter(todo => !todo.done)
    }
    
  },
  //组件
  components: {
    MyHeader,
    MyList,
    MyFooter,
  },
  //监视属性
  watch: {
    todos: {
      deep: true,
      handler(value) {
        //重新存储
        localStorage.setItem('todos', JSON.stringify(value))
        if (this.todos.length > 0) {
          this.allChecked = !this.todos.some(function (todo) {
                if (!todo.done) {//存在false
                  return true
                }
              }
          )
        } else {
          this.allChecked = false
        }

      }
    },
    allChecked: {
      handler(value) {
        console.log('值被修改')
        localStorage.setItem('allChecked', value)
      }
    }
  },
  //生命周期函数
  mounted() {
    //通过消息订阅传递
    this.pidId = pubsub.subscribe('changeCheck', this.changeCheck)
    //通过全局事件总线将MyItem组件的参数传给App
    this.$bus.$on('deleteTodo', this.deleteTodo)
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.pidId)
  }
}
</script>

<template>
  <div class="demo">
    <!--    通过自定义事件将需要添加的任务对象通过MyHeader传给App-->
    <MyHeader @addTodo="addTodo"/>
    <MyList v-bind:todos="todos"/>
    <MyFooter :todos="todos" :allChecked="this.allChecked" @allChangeTodo="checkAllTodo" @cleanTodo="clearAllTodo"/>
  </div>
</template>

<style>
.demo {
  width: 800px;
  border: 1px solid black;
  margin: auto;
}

li button {
  border-radius: 5px;
  margin-right: 5px;
  margin-top: 3px;
  float: right;
  background-color: wheat;
}
</style>